{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Semantic QA over tables\n",
    "\n",
    "https://docs.llamaindex.ai/en/stable/examples/query_engine/sec_tables/tesla_10q_table.html#extract-elements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydantic import BaseModel\n",
    "from unstructured.partition.html import partition_html\n",
    "import pandas as pd\n",
    "\n",
    "pd.set_option(\"display.max_rows\", None)\n",
    "pd.set_option(\"display.max_columns\", None)\n",
    "pd.set_option(\"display.width\", None)\n",
    "pd.set_option(\"display.max_colwidth\", None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load pdfs\n",
    "from llama_index import SimpleDirectoryReader\n",
    "from llama_index.readers.file.flat_reader import FlatReader\n",
    "\n",
    "company = \"meta\"\n",
    "\n",
    "if company == \"apple\":\n",
    "    reader = SimpleDirectoryReader(\n",
    "        input_files=[\"../data/apple/AAPL.pdf\"]\n",
    "    )\n",
    "    docs = reader.load_data()\n",
    "\n",
    "\n",
    "elif company ==\"meta\":\n",
    "    reader = SimpleDirectoryReader(\n",
    "        input_files=[\"../data/meta/meta.pdf\"]\n",
    "    )\n",
    "\n",
    "    docs = reader.load_data()\n",
    "\n",
    "# reader  = FlatReader()\n",
    "# docs1 = reader.load_data(Path(\"../data/apple/AAPL.pdf\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'wefwe' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m/Users/vishwasgowda/Desktop/FinSight/experiments/semantic_qa_over_tables.ipynb Cell 4\u001b[0m line \u001b[0;36m1\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/vishwasgowda/Desktop/FinSight/experiments/semantic_qa_over_tables.ipynb#X14sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m wefwe\n",
      "\u001b[0;31mNameError\u001b[0m: name 'wefwe' is not defined"
     ]
    }
   ],
   "source": [
    "wefwe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "0it [00:00, ?it/s]"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\n"
     ]
    }
   ],
   "source": [
    "from llama_index.node_parser import UnstructuredElementNodeParser\n",
    "\n",
    "node_parser = UnstructuredElementNodeParser()\n",
    "nodes = node_parser.get_nodes_from_documents(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.retrievers import RecursiveRetriever\n",
    "from llama_index.query_engine import RetrieverQueryEngine\n",
    "from llama_index import VectorStoreIndex\n",
    "\n",
    "vector_index = VectorStoreIndex(nodes)\n",
    "vector_retriever = vector_index.as_retriever(similarity_top_k=2)\n",
    "vector_query_engine = vector_index.as_query_engine(similarity_top_k=2)\n",
    "\n",
    "from llama_index.retrievers import RecursiveRetriever\n",
    "\n",
    "recursive_retriever = RecursiveRetriever(\n",
    "    \"vector\",\n",
    "    retriever_dict={\"vector\": vector_retriever},\n",
    "    verbose=True,\n",
    ")\n",
    "query_engine = RetrieverQueryEngine.from_args(recursive_retriever)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# response = query_engine.query(\"what was the management's discussion and analysis\")\n",
    "# print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "env_file_path = \"../.env\"\n",
    "load_dotenv(dotenv_path=env_file_path)\n",
    "api_key = os.environ.get(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.tools import QueryEngineTool, ToolMetadata\n",
    "from llama_index.query_engine import SubQuestionQueryEngine\n",
    "\n",
    "from llama_index import ServiceContext\n",
    "from llama_index.llms import OpenAI\n",
    "\n",
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()\n",
    "\n",
    "llm = OpenAI(model=\"gpt-3.5-turbo\", api_key=api_key)\n",
    "service_context = ServiceContext.from_defaults(llm=llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine_tool = [\n",
    "    QueryEngineTool(\n",
    "        query_engine=query_engine,\n",
    "        metadata=ToolMetadata(\n",
    "            name = company,\n",
    "            description=f\"provides information about {company} financials for the year 2022\",\n",
    "        ),\n",
    "    )\n",
    "]\n",
    "\n",
    "sub_query_engine = SubQuestionQueryEngine.from_defaults(\n",
    "    query_engine_tools=query_engine_tool,\n",
    "    service_context=service_context,\n",
    "    use_async=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated 3 sub questions.\n",
      "\u001b[1;3;38;2;237;90;200m[apple] Q: What are the financial risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;34mRetrieving with query id None: What are the financial risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: Item 1A. Risk Factors\n",
      "The Company’s business, reputation, results of operations, financial condition and stock price can be affected by a number of \n",
      "factors, whether currently known or unknown, including those described below. When any one or more of these risks materialize \n",
      "from time to time, the Company’s business, reputation, results of operations, financial condition and stock price can be materially \n",
      "and adversely affected.\n",
      "Because of the following factors, as well as other factors affecting the Company’s results of operations and financial condition, \n",
      "past financial performance should not be considered to be a reliable indicator of future performance, and investors should not \n",
      "use historical trends to anticipate results or trends in future periods. This discussion of risk factors contains forward-looking \n",
      "statements.\n",
      "This section should be read in conjunction with Part II, Item 7, “Management’s Discussion and Analysis of Financial Condition \n",
      "and Results of Operations” and the consolidated financial statements and accompanying notes in Part II, Item 8, “Financial \n",
      "Statements and Supplementary Data” of this Form 10-K.\n",
      "Macroeconomic and Industry Risks\n",
      "The Company’s operations and performance depend significantly on global and regional economic conditions and \n",
      "adverse economic conditions can materially adversely affect the Company’s business, results of operations and financial \n",
      "condition .\n",
      "The Company has international operations with sales outside the U.S. representing a majority of the Company’s total net sales. \n",
      "In addition, the Company’s global supply chain is large and complex and a majority of the Company’s supplier facilities, including \n",
      "manufacturing and assembly sites, are located outside the U.S. As a result, the Company’s operations and performance depend \n",
      "significantly on global and regional economic conditions.\n",
      "Adverse macroeconomic conditions, including inflation, slower growth or recession, new or increased tariffs and other barriers to \n",
      "trade, changes to fiscal and monetary policy, tighter credit, higher interest rates, high unemployment and currency fluctuations \n",
      "can adversely impact consumer confidence and spending and materially adversely affect demand for the Company’s products \n",
      "and services. In addition, consumer confidence and spending can be materially adversely affected in response to financial \n",
      "market volatility, negative financial news, conditions in the real estate and mortgage markets, declines in income or asset values, \n",
      "energy shortages and cost increases, labor and healthcare costs and other economic factors. \n",
      "In addition to an adverse impact on demand for the Company’s products, uncertainty about, or a decline in, global or regional \n",
      "economic conditions can have a significant impact on the Company’s suppliers, contract manufacturers, logistics providers, \n",
      "distributors, cellular network carriers and other channel partners. Potential effects include financial instability; inability to obtain \n",
      "credit to finance operations and purchases of the Company’s products; and insolvency.\n",
      "A downturn in the economic environment can also lead to increased credit and collectibility risk on the Company’s trade \n",
      "receivables; the failure of derivative counterparties and other financial institutions; limitations on the Company’s ability to issue \n",
      "new debt; reduced liquidity; and declines in the fair value of the Company’s financial instruments. These and other economic \n",
      "factors can materially adversely affect the Company’s business, results of operations, financial condition and stock  price .\n",
      "The Company’s business, results of operations, financial condition and stock price have been adversely affected and \n",
      "could in the future be materially adversely affected by the COVID-19 pandemic.\n",
      "COVID-19 has had, and continues to have, a significant impact around the world, prompting governments and businesses to \n",
      "take unprecedented measures in response. Such measures have included restrictions on travel and business operations, \n",
      "temporary closures of businesses, and quarantine and shelter-in-place orders. The COVID-19 pandemic has at times \n",
      "significantly curtailed global economic activity and caused significant volatility and disruption in global financial ma rkets.\n",
      "The COVID-19 pandemic and the measures taken by many countries in response have adversely affected and could in the \n",
      "future materially adversely impact the Company’s business, results of operations, financial condition and stock price. During the \n",
      "course of the pandemic, certain of the Company’s component suppliers and manufacturing and logistical service providers have \n",
      "experienced disruptions, resulting in supply shortages that affected sales worldwide, and similar disruptions could occur in the \n",
      "future . Public safety measures can also adversely impact consumer demand for the Company’s products and services in \n",
      "affected areas.\n",
      "Apple Inc. | 2022  Form 10-K | 5\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: Legal and Regulatory Compliance Risks\n",
      "The Company’s business, results of operations and financial condition could be adversely impacted by unfavorable \n",
      "results of legal proceedings or government investigations.\n",
      "The Company is subject to various claims, legal proceedings and government investigations that have arisen in the ordinary \n",
      "course of business and have not yet been fully resolved, and new matters may arise in the future. In addition, agreements \n",
      "entered into by the Company sometimes include indemnification provisions which can subject the Company to costs and \n",
      "damages in the event of a claim against an indemnified third party. The number of claims, legal proceedings and government \n",
      "investigations involving the Company, and the alleged magnitude of such claims, proceedings and government investigations, \n",
      "has generally increased over time and may continue to increase.\n",
      "The Company has faced and continues to face a significant number of patent claims relating to its cellular-enabled products, and \n",
      "new claims may arise in the future. For example, technology and other patent-holding companies frequently assert their patents \n",
      "and seek royalties and often enter into litigation based on allegations of patent infringement or other violations of intellectual \n",
      "property rights. The Company is vigorously defending infringement actions in courts in several U.S. jurisdictions, as well as \n",
      "internationally in various countries. The plaintiffs in these actions frequently seek injunctions and substantial damages.\n",
      "Regardless of the merit of particular claims, defending against litigation or responding to government investigations can be \n",
      "expensive, time-consuming and disruptive to the Company’s operations. In recognition of these considerations, the Company \n",
      "may enter into agreements or other arrangements to settle litigation and resolve such challenges. There can be no assurance \n",
      "such agreements can be obtained on acceptable terms or that litigation will not occur. These agreements can also significantly \n",
      "increase the Company’s cost of sales and operating expenses and require the Company to change its business practices and \n",
      "limit the Company’s ability to offer certain products and services.\n",
      "Except as described in Part I, Item 3 of this Form 10-K under the heading “Legal Proceedings” and in Part II, Item 8 of this Form \n",
      "10-K in the Notes to Consolidated Financial Statements in Note 10, “Commitments and Contingencies” under the heading \n",
      "“Contingencies,” in the opinion of management, there was not at least a reasonable possibility the Company may have incurred a \n",
      "material loss, or a material loss greater than a recorded accrual, concerning loss contingencies for asserted legal and other \n",
      "claims.\n",
      "The outcome of litigation or government investigations is inherently uncertain. If one or more legal matters were resolved against \n",
      "the Company or an indemnified third party in a reporting period for amounts above management’s expectations, the Company’s \n",
      "results of operations and financial condition for that reporting period could be materially adversely affected. Further, such an \n",
      "outcome can result in significant compensatory, punitive or trebled monetary damages, disgorgement of revenue or profits, \n",
      "remedial corporate measures or injunctive relief against the Company, and can require the Company to change its business \n",
      "practices and limit the Company’s ability to offer certain products and services, all of which could materially adversely affect the \n",
      "Company’s business, reputation, results of operations and financial condition.\n",
      "While the Company maintains insurance coverage for certain types of claims, such insurance coverage may be insufficient to \n",
      "cover all losses or all types of claims that may arise.\n",
      "The Company is subject to complex and changing laws and regulations worldwide, which exposes the Company to \n",
      "potential liabilities, increased costs and other adverse effects on the Company’s business.\n",
      "The Company’s global operations are subject to complex and changing laws and regulations on subjects, including antitrust; \n",
      "privacy, data security and data localization; consumer protection; advertising, sales, billing and e-commerce; financial services \n",
      "and technology; product liability; intellectual property ownership and infringement; digital platforms; internet , telecommunications, \n",
      "and mobile communications; media, television, film and digital content; availability of third-party software applications and \n",
      "services; labor and employment; anticorruption; import, export and trade; foreign exchange controls and cash repatriation \n",
      "restrictions; anti–money laundering; foreign ownership and investment; tax; and environmental, health and safety, including \n",
      "electronic waste, recycling, and climate change.\n",
      "Apple Inc. | 2022  Form 10-K | 13\n",
      "\u001b[0m\u001b[1;3;38;2;90;149;237m[apple] Q: What are the operational risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;34mRetrieving with query id None: What are the operational risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: Business Risks\n",
      "To remain competitive and stimulate customer demand, the Company must successfully manage frequent introductions \n",
      "and transitions of products and services.\n",
      "Due to the highly volatile and competitive nature of the markets and industries in which the Company competes, the Company \n",
      "must continually introduce new products, services and technologies, enhance existing products and services, effectively \n",
      "stimulate customer demand for new and upgraded products and services, and successfully manage the transition to these new \n",
      "and upgraded products and services. The success of new product and service introductions depends on a number of factors, \n",
      "including timely and successful development, market acceptance, the Company’s ability to manage the risks associated with \n",
      "production ramp-up issues, the availability of application software for the Company’s products, the effective management of \n",
      "purchase commitments and inventory levels in line with anticipated product demand, the availability of products in appropriate \n",
      "quantities and at expected costs to meet anticipated demand, and the risk that new products and services may have quality or \n",
      "other defects or deficiencies. There can be no assurance the Company will successfully manage future introductions and \n",
      "transitions of products and services.\n",
      "The Company depends on component and product manufacturing and logistical services provided by outsourcing \n",
      "partners, many of which are located outside of the U.S.\n",
      "Substantially all of the Company’s manufacturing is performed in whole or in part by outsourcing partners located primarily in \n",
      "Asia, including China mainland, India, Japan, South Korea, Taiwan and Vietnam, and a significant concentration of this \n",
      "manufacturing is currently performed by a small number of outsourcing partners, often in single locations. Changes or additions \n",
      "to the Company’s supply chain require considerable time and resources and involve significant risks and uncertainties. The \n",
      "Company has also outsourced much of its transportation and logistics management. While these arrangements can lower \n",
      "operating costs, they also reduce the Company’s direct control over production and distribution. Such diminished control has \n",
      "from time to time and may in the future have an adverse effect on the quality or quantity of products manufactured or services \n",
      "provided, or adversely affect the Company’s flexibility to respond to changing conditions. Although arrangements with these \n",
      "partners may contain provisions for product defect expense reimbursement, the Company generally remains responsible to the \n",
      "consumer for warranty and out-of-warranty service in the event of product defects and experiences unanticipated product defect \n",
      "liabilities from time to time. While the Company relies on its partners to adhere to its supplier code of conduct, violations of the \n",
      "supplier code of conduct occur from time to time and can materially adversely affect the Company’s business, reputation, results \n",
      "of operations and financial condition.\n",
      "The Company relies on single-source outsourcing partners in the U.S., Asia and Europe to supply and manufacture many \n",
      "components, and on outsourcing partners primarily located in Asia, for final assembly of substantially all of the Company’s \n",
      "hardware products. Any failure of these partners to perform can have a negative impact on the Company’s cost or supply of \n",
      "components or finished goods. In addition, manufacturing or logistics in these locations or transit to final destinations can be \n",
      "disrupted for a variety of reasons, including natural and man-made disasters, information technology system failures, commercial \n",
      "disputes, armed conflict, economic, business, labor, environmental, public health or political issues, or international trade \n",
      "disputes.\n",
      "The Company has invested in manufacturing process equipment, much of which is held at certain of its outsourcing partners, \n",
      "and has made prepayments to certain of its suppliers associated with long-term supply agreements. While these arrangements \n",
      "help ensure the supply of components and finished goods, if these outsourcing partners or suppliers experience severe financial \n",
      "problems or other disruptions in their business, such continued supply can be reduced or terminated, and the recoverability of \n",
      "manufacturing process equipment or prepayments can be negatively impacted.\n",
      "Future operating results depend upon the Company’s ability to obtain components in sufficient quantities on \n",
      "commercially reasonable terms.\n",
      "Because the Company currently obtains certain components from single or limited sources, the Company is subject to significant \n",
      "supply and pricing risks. Many components, including those that are available from multiple sources, are at times subject to \n",
      "industry-wide shortages and significant commodity pricing fluctuations that can materially adversely affect the Company’s \n",
      "business, results of operations and financial condition. For example, the global semiconductor industry is experiencing high \n",
      "demand and shortages of supply, which has adversely affected, and could materially adversely affect, the Company’s ability to \n",
      "obtain sufficient quantities of components and products on commercially reasonable terms or at all.\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: The Company’s operations are also subject to the risks of industrial accidents at its suppliers and contract manufacturers. While \n",
      "the Company’s suppliers are required to maintain safe working environments and operations, an industrial accident could occur \n",
      "and could result in serious injuries or loss of life, disruption to the Company’s business, and harm to the Company’s reputation. \n",
      "Major public health issues, including pandemics such as the COVID-19 pandemic, have adversely affected, and could in the \n",
      "future materially adversely affect, the Company due to their impact on the global economy and demand for consumer products; \n",
      "the imposition of protective public safety measures, such as stringent employee travel restrictions and limitations on freight \n",
      "services and the movement of products between regions; and disruptions in the Company’s supply chain and sales and \n",
      "distribution channels, resulting in interruptions of the supply of current products and delays in production ramps of new products.\n",
      "While the Company maintains insurance coverage for certain types of losses, such insurance coverage may be insufficient to \n",
      "cover all losses that may arise.\n",
      "Global markets for the Company’s products and services are highly competitive and subject to rapid technological \n",
      "change, and the Company may be unable to compete effectively in these markets.\n",
      "The Company’s products and services are offered in highly competitive global markets characterized by aggressive price \n",
      "competition and resulting downward pressure on gross margins, frequent introduction of new products and services, short \n",
      "product life cycles, evolving industry standards, continual improvement in product price and performance characteristics, rapid \n",
      "adoption of technological advancements by competitors, and price sensitivity on the part of consumers and businesses.\n",
      "The Company’s ability to compete successfully depends heavily on ensuring the continuing and timely introduction of innovative \n",
      "new products, services and technologies to the marketplace. The Company designs and develops nearly the entire solution for \n",
      "its products, including the hardware, operating system, numerous software applications and related services. As a result, the \n",
      "Company must make significant investments in R&D. There can be no assurance these investments will achieve expected \n",
      "returns, and the Company may not be able to develop and market new products and services successfully.\n",
      "The Company currently holds a significant number of patents, trademarks and copyrights and has registered, and applied to \n",
      "register, additional patents, trademarks and copyrights. In contrast, many of the Company’s competitors seek to compete \n",
      "primarily through aggressive pricing and very low cost structures, and by imitating the Company’s products and infringing on \n",
      "its  intellectual property. Effective intellectual property protection is not consistently available in every country in which the \n",
      "Company operates. If the Company is unable to continue to develop and sell innovative new products with attractive margins or if \n",
      "competitors infringe on the Company’s intellectual property, the Company’s ability to maintain a competitive advantage could be \n",
      "materially adversely affected.\n",
      "The Company has a minority market share in the global smartphone, personal computer and tablet markets. The Company faces \n",
      "substantial competition in these markets from companies that have significant technical, marketing, distribution and other \n",
      "resources, as well as established hardware, software and digital content supplier relationships. In addition, some of the \n",
      "Company’s competitors have broader product lines, lower-priced products and a larger installed base of active devices. \n",
      "Competition has been particularly intense as competitors have aggressively cut prices and lowered product margins. Certain \n",
      "competitors have the resources, experience or cost structures to provide products at little or no profit or even at a loss. Some of \n",
      "the markets in which the Company competes have from time to time experienced little to no growth or contracted overall.\n",
      "Additionally, the Company faces significant competition as competitors imitate the Company’s product features and applications \n",
      "within their products or collaborate to offer solutions that are more competitive than those they currently offer. The Company also \n",
      "expects competition to intensify as competitors imitate the Company’s approach to providing components seamlessly within their \n",
      "offerings or work collaboratively to offer integrated solutions.\n",
      "The Company’s services also face substantial competition, including from companies that have significant resources and \n",
      "experience and have established service offerings with large customer bases. The Company competes with business models \n",
      "that provide content to users for free. The Company also competes with illegitimate means to obtain third-party digital content \n",
      "and applications.\n",
      "The Company’s business, results of operations and financial condition depend substantially on the Company’s ability to \n",
      "continually improve its products and services to maintain their functional and design advantages. There can be no assurance the \n",
      "Company will be able to continue to provide products and services that compete effectively.\n",
      "Apple Inc. | 2022  Form 10-K | 7\n",
      "\u001b[0m\u001b[1;3;38;2;11;159;203m[apple] Q: What are the market risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;34mRetrieving with query id None: What are the market risks faced by the company?\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: Business Risks\n",
      "To remain competitive and stimulate customer demand, the Company must successfully manage frequent introductions \n",
      "and transitions of products and services.\n",
      "Due to the highly volatile and competitive nature of the markets and industries in which the Company competes, the Company \n",
      "must continually introduce new products, services and technologies, enhance existing products and services, effectively \n",
      "stimulate customer demand for new and upgraded products and services, and successfully manage the transition to these new \n",
      "and upgraded products and services. The success of new product and service introductions depends on a number of factors, \n",
      "including timely and successful development, market acceptance, the Company’s ability to manage the risks associated with \n",
      "production ramp-up issues, the availability of application software for the Company’s products, the effective management of \n",
      "purchase commitments and inventory levels in line with anticipated product demand, the availability of products in appropriate \n",
      "quantities and at expected costs to meet anticipated demand, and the risk that new products and services may have quality or \n",
      "other defects or deficiencies. There can be no assurance the Company will successfully manage future introductions and \n",
      "transitions of products and services.\n",
      "The Company depends on component and product manufacturing and logistical services provided by outsourcing \n",
      "partners, many of which are located outside of the U.S.\n",
      "Substantially all of the Company’s manufacturing is performed in whole or in part by outsourcing partners located primarily in \n",
      "Asia, including China mainland, India, Japan, South Korea, Taiwan and Vietnam, and a significant concentration of this \n",
      "manufacturing is currently performed by a small number of outsourcing partners, often in single locations. Changes or additions \n",
      "to the Company’s supply chain require considerable time and resources and involve significant risks and uncertainties. The \n",
      "Company has also outsourced much of its transportation and logistics management. While these arrangements can lower \n",
      "operating costs, they also reduce the Company’s direct control over production and distribution. Such diminished control has \n",
      "from time to time and may in the future have an adverse effect on the quality or quantity of products manufactured or services \n",
      "provided, or adversely affect the Company’s flexibility to respond to changing conditions. Although arrangements with these \n",
      "partners may contain provisions for product defect expense reimbursement, the Company generally remains responsible to the \n",
      "consumer for warranty and out-of-warranty service in the event of product defects and experiences unanticipated product defect \n",
      "liabilities from time to time. While the Company relies on its partners to adhere to its supplier code of conduct, violations of the \n",
      "supplier code of conduct occur from time to time and can materially adversely affect the Company’s business, reputation, results \n",
      "of operations and financial condition.\n",
      "The Company relies on single-source outsourcing partners in the U.S., Asia and Europe to supply and manufacture many \n",
      "components, and on outsourcing partners primarily located in Asia, for final assembly of substantially all of the Company’s \n",
      "hardware products. Any failure of these partners to perform can have a negative impact on the Company’s cost or supply of \n",
      "components or finished goods. In addition, manufacturing or logistics in these locations or transit to final destinations can be \n",
      "disrupted for a variety of reasons, including natural and man-made disasters, information technology system failures, commercial \n",
      "disputes, armed conflict, economic, business, labor, environmental, public health or political issues, or international trade \n",
      "disputes.\n",
      "The Company has invested in manufacturing process equipment, much of which is held at certain of its outsourcing partners, \n",
      "and has made prepayments to certain of its suppliers associated with long-term supply agreements. While these arrangements \n",
      "help ensure the supply of components and finished goods, if these outsourcing partners or suppliers experience severe financial \n",
      "problems or other disruptions in their business, such continued supply can be reduced or terminated, and the recoverability of \n",
      "manufacturing process equipment or prepayments can be negatively impacted.\n",
      "Future operating results depend upon the Company’s ability to obtain components in sufficient quantities on \n",
      "commercially reasonable terms.\n",
      "Because the Company currently obtains certain components from single or limited sources, the Company is subject to significant \n",
      "supply and pricing risks. Many components, including those that are available from multiple sources, are at times subject to \n",
      "industry-wide shortages and significant commodity pricing fluctuations that can materially adversely affect the Company’s \n",
      "business, results of operations and financial condition. For example, the global semiconductor industry is experiencing high \n",
      "demand and shortages of supply, which has adversely affected, and could materially adversely affect, the Company’s ability to \n",
      "obtain sufficient quantities of components and products on commercially reasonable terms or at all.\n",
      "\u001b[0m\u001b[1;3;38;5;200mRetrieving text node: The Company’s operations are also subject to the risks of industrial accidents at its suppliers and contract manufacturers. While \n",
      "the Company’s suppliers are required to maintain safe working environments and operations, an industrial accident could occur \n",
      "and could result in serious injuries or loss of life, disruption to the Company’s business, and harm to the Company’s reputation. \n",
      "Major public health issues, including pandemics such as the COVID-19 pandemic, have adversely affected, and could in the \n",
      "future materially adversely affect, the Company due to their impact on the global economy and demand for consumer products; \n",
      "the imposition of protective public safety measures, such as stringent employee travel restrictions and limitations on freight \n",
      "services and the movement of products between regions; and disruptions in the Company’s supply chain and sales and \n",
      "distribution channels, resulting in interruptions of the supply of current products and delays in production ramps of new products.\n",
      "While the Company maintains insurance coverage for certain types of losses, such insurance coverage may be insufficient to \n",
      "cover all losses that may arise.\n",
      "Global markets for the Company’s products and services are highly competitive and subject to rapid technological \n",
      "change, and the Company may be unable to compete effectively in these markets.\n",
      "The Company’s products and services are offered in highly competitive global markets characterized by aggressive price \n",
      "competition and resulting downward pressure on gross margins, frequent introduction of new products and services, short \n",
      "product life cycles, evolving industry standards, continual improvement in product price and performance characteristics, rapid \n",
      "adoption of technological advancements by competitors, and price sensitivity on the part of consumers and businesses.\n",
      "The Company’s ability to compete successfully depends heavily on ensuring the continuing and timely introduction of innovative \n",
      "new products, services and technologies to the marketplace. The Company designs and develops nearly the entire solution for \n",
      "its products, including the hardware, operating system, numerous software applications and related services. As a result, the \n",
      "Company must make significant investments in R&D. There can be no assurance these investments will achieve expected \n",
      "returns, and the Company may not be able to develop and market new products and services successfully.\n",
      "The Company currently holds a significant number of patents, trademarks and copyrights and has registered, and applied to \n",
      "register, additional patents, trademarks and copyrights. In contrast, many of the Company’s competitors seek to compete \n",
      "primarily through aggressive pricing and very low cost structures, and by imitating the Company’s products and infringing on \n",
      "its  intellectual property. Effective intellectual property protection is not consistently available in every country in which the \n",
      "Company operates. If the Company is unable to continue to develop and sell innovative new products with attractive margins or if \n",
      "competitors infringe on the Company’s intellectual property, the Company’s ability to maintain a competitive advantage could be \n",
      "materially adversely affected.\n",
      "The Company has a minority market share in the global smartphone, personal computer and tablet markets. The Company faces \n",
      "substantial competition in these markets from companies that have significant technical, marketing, distribution and other \n",
      "resources, as well as established hardware, software and digital content supplier relationships. In addition, some of the \n",
      "Company’s competitors have broader product lines, lower-priced products and a larger installed base of active devices. \n",
      "Competition has been particularly intense as competitors have aggressively cut prices and lowered product margins. Certain \n",
      "competitors have the resources, experience or cost structures to provide products at little or no profit or even at a loss. Some of \n",
      "the markets in which the Company competes have from time to time experienced little to no growth or contracted overall.\n",
      "Additionally, the Company faces significant competition as competitors imitate the Company’s product features and applications \n",
      "within their products or collaborate to offer solutions that are more competitive than those they currently offer. The Company also \n",
      "expects competition to intensify as competitors imitate the Company’s approach to providing components seamlessly within their \n",
      "offerings or work collaboratively to offer integrated solutions.\n",
      "The Company’s services also face substantial competition, including from companies that have significant resources and \n",
      "experience and have established service offerings with large customer bases. The Company competes with business models \n",
      "that provide content to users for free. The Company also competes with illegitimate means to obtain third-party digital content \n",
      "and applications.\n",
      "The Company’s business, results of operations and financial condition depend substantially on the Company’s ability to \n",
      "continually improve its products and services to maintain their functional and design advantages. There can be no assurance the \n",
      "Company will be able to continue to provide products and services that compete effectively.\n",
      "Apple Inc. | 2022  Form 10-K | 7\n",
      "\u001b[0m\u001b[1;3;38;2;90;149;237m[apple] A: The operational risks faced by the company include the need to manage frequent introductions and transitions of products and services, reliance on outsourcing partners for manufacturing and logistical services, dependence on single-source outsourcing partners for components and final assembly, potential disruptions in manufacturing or logistics due to various reasons, potential financial problems or disruptions in business of outsourcing partners or suppliers, supply and pricing risks due to industry-wide shortages and commodity pricing fluctuations, risks of industrial accidents at suppliers and contract manufacturers, potential impact of major public health issues on the global economy and supply chain, potential insufficiency of insurance coverage for losses, intense competition in global markets characterized by aggressive price competition and rapid technological change, the need to continually introduce innovative new products and services, the need for effective intellectual property protection, competition from companies with significant resources and established relationships, and the need to continually improve products and services to maintain their advantages.\n",
      "\u001b[0m\u001b[1;3;38;2;237;90;200m[apple] A: The company faces financial risks due to various factors. Adverse macroeconomic conditions such as inflation, slower growth or recession, new or increased tariffs, changes to fiscal and monetary policy, tighter credit, higher interest rates, high unemployment, and currency fluctuations can adversely impact consumer confidence and spending, which can materially affect demand for the company's products and services. Uncertainty or a decline in global or regional economic conditions can also have a significant impact on the company's suppliers, contract manufacturers, logistics providers, distributors, cellular network carriers, and other channel partners. Additionally, the COVID-19 pandemic has adversely affected the company's business, results of operations, financial condition, and stock price. The pandemic has caused significant volatility and disruption in global financial markets, resulting in supply shortages and reduced consumer demand for the company's products and services. Furthermore, the company's financial condition can be adversely impacted by unfavorable results of legal proceedings or government investigations, as well as the costs and damages associated with indemnification provisions in agreements. The company is subject to various claims, legal proceedings, and patent claims, which can be expensive, time-consuming, and disruptive to its operations. It is important to note that the outcome of litigation or government investigations is uncertain and can result in significant monetary damages, remedial measures, injunctive relief, and changes in business practices, all of which can materially affect the company's business, reputation, results of operations, and financial condition.\n",
      "\u001b[0m\u001b[1;3;38;2;11;159;203m[apple] A: The Company faces several market risks. These include aggressive price competition, downward pressure on gross margins, frequent introduction of new products and services by competitors, short product life cycles, evolving industry standards, rapid adoption of technological advancements by competitors, and price sensitivity on the part of consumers and businesses. Additionally, the Company has a minority market share in the global smartphone, personal computer, and tablet markets, and faces substantial competition from companies with significant technical, marketing, distribution, and other resources. Some competitors have broader product lines, lower-priced products, and a larger installed base of active devices. The Company also faces competition as competitors imitate its product features and applications or collaborate to offer more competitive solutions.\n",
      "\u001b[0m--------------------------------------------------\n",
      "- Frequent introductions and transitions of products and services\n",
      "- Reliance on outsourcing partners for manufacturing and logistical services\n",
      "- Dependence on single-source outsourcing partners for components and final assembly\n",
      "- Potential disruptions in manufacturing or logistics\n",
      "- Potential financial problems or disruptions in business of outsourcing partners or suppliers\n",
      "- Supply and pricing risks due to industry-wide shortages and commodity pricing fluctuations\n",
      "- Risks of industrial accidents at suppliers and contract manufacturers\n",
      "- Potential impact of major public health issues on the global economy and supply chain\n",
      "- Potential insufficiency of insurance coverage for losses\n",
      "- Intense competition in global markets characterized by aggressive price competition and rapid technological change\n",
      "- The need to continually introduce innovative new products and services\n",
      "- The need for effective intellectual property protection\n",
      "- Competition from companies with significant resources and established relationships\n",
      "- The need to continually improve products and services to maintain their advantages.\n"
     ]
    }
   ],
   "source": [
    "query = \"\"\"\n",
    "what are the risks faced in day to day operations by the company? List them out using bullet points.\n",
    "\"\"\"\n",
    "\n",
    "response = sub_query_engine.query(query)\n",
    "print(\"-\"*50)\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "- Frequent introductions and transitions of products and services\n",
      "- Reliance on outsourcing partners for manufacturing and logistical services\n",
      "- Dependence on single-source outsourcing partners for components and final assembly\n",
      "- Potential disruptions in manufacturing or logistics\n",
      "- Potential financial problems or disruptions in business of outsourcing partners or suppliers\n",
      "- Supply and pricing risks due to industry-wide shortages and commodity pricing fluctuations\n",
      "- Risks of industrial accidents at suppliers and contract manufacturers\n",
      "- Potential impact of major public health issues on the global economy and supply chain\n",
      "- Potential insufficiency of insurance coverage for losses\n",
      "- Intense competition in global markets characterized by aggressive price competition and rapid technological change\n",
      "- The need to continually introduce innovative new products and services\n",
      "- The need for effective intellectual property protection\n",
      "- Competition from companies with significant resources and established relationships\n",
      "- The need to continually improve products and services to maintain their advantages.\n"
     ]
    }
   ],
   "source": [
    "print(str(response))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
